package top.jfunc.validation.spring;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

/**
 * @author xiongshiyan at 2019/9/28 , contact me with email yanshixiong@126.com or phone 15208384257
 */
public class ValidateUtil {
    /**
     * 在切面方法前调用此方法，根据注解{@link Validated}指定的{@link Validator}校验方法的参数
     * @param applicationContext ApplicationContext
     */
    public static void validateJoinPointParams(ApplicationContext applicationContext , Method method , Object[] args) {
        ///Validated validated = AnnotationUtil.getValidated(method);

        Validated[] validatedes = AnnotationUtil.getValidatedes(method);

        if(null == validatedes || 0 == validatedes.length){
            return;
        }

        for (Validated validated : validatedes) {
            //存在@Validated注解
            Class<? extends Validator>[] validatorClasses = validated.value();
            for (Class<? extends Validator> validatorClass : validatorClasses) {
                Validator validator = getOrCreateValidator(applicationContext, validatorClass);
                validator.validate(args);
            }
        }


    }

    private static Validator getOrCreateValidator(ApplicationContext applicationContext, Class<? extends Validator> validatorClass) {
        String fromcontainer = applicationContext.getEnvironment().getProperty("validation.validator.fromcontainer" , "true");

        //不从容器中找校验器
        if("false".equals(fromcontainer)){
            return BeanUtils.instantiateClass(validatorClass);
        }


        try {
            //先从容器中找
            return applicationContext.getBean(validatorClass);
        } catch (BeansException e) {
            //找不到再自己实例化
            return BeanUtils.instantiateClass(validatorClass);
        }
    }
}
